/**
 * 
 * 可通过 $page 获取或修改当前页面的 变量 状态 handler lifecycle 等信息
 * 可通过 app 获取或修改全局应用的 变量 状态 等信息
 * 具体可以console.info 在编辑器Console面板查看更多信息
 * 注意：该方法仅在所属的页面有效
 * 如果需要 async-await，请修改成 export default async function() {}
 * 帮助文档 https://cloud.tencent.com/document/product/1301/57912
 **/

/**
 * @param {Object} event - 事件对象
 * @param {string} event.type - 事件名
 * @param {any} event.detail - 事件携带自定义数据
 *
 * @param {Object} data
 * @param {any} data.target - 获取事件传参的数据
 **/
const verifyCodeFailedLimit = 8; // 同一个短信验证码使用8次即提示错误

const authVerify = async (params) => {
  const auth = (await $w.cloud.getCloudInstance()).authInstance;
  try {
    const data = await auth.verify({
      verification_id: params.verification_id,
      verification_code: params.verification_code,
    });
    return data;
  } catch (error) {
    console.log('=======> authVerify err', error);
    return error;
  }
};

export default async function(params) {
  $w.page.dataset.state.loading = true;
  const values = params.data?.target;
  const { usedCount = 0 } = $w.page.handler.getPhoneStorage() || {};

  try {
    // 验证码使用次数超过限制，直接提示错误
    if (usedCount >= verifyCodeFailedLimit) {
      $w.page.dataset.state.alertInfo = { message: '验证码使用次数超过限制', type: 'error' };
      $w.page.dataset.state.loading = false;
      return;
    }

    // 1. 验证验证码
    const data = await authVerify({
      verification_id: $w.page.dataset.state.verificationCodeInfo.verification_id,
      verification_code: `${values.code}`,
    });

    if (data?.error_code) {
      $w.page.dataset.state.alertInfo = { message: $w.page.handler.parseSmsError(data), type: 'error' };
      $w.page.dataset.state.loading = false;
      return;
    }

    const result = await $w.page.handler.updateUserBasicInfo({
      data: { target: { phone: `+86 ${values.phone}`, user_id: $w.page.dataset.state.userInfo.user_id } }
    });

    if (result?.error_code) {
      $w.page.dataset.state.alertInfo = { message: $w.page.handler.parseSmsError(result), type: 'error' };
      $w.page.dataset.state.loading = false;
      return;
    }

    $w.page.handler.setPhoneStorage({ usedCount: 0, smsDelay: 0 });
    $w.page.dataset.state.loading = false;
    $w.utils.showToast({ title: '操作成功' });
  } catch (e) {
    $w.page.dataset.state.alertInfo = { message: $w.page.handler.parseSmsError(e), type: 'error' };
    $w.page.dataset.state.loading = false;
    $w.page.handler.setPhoneStorage({ usedCount: usedCount + 1 });
  }

  $w.modal2.close({});
  return;
}